/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author haolw
 * @time 2017/07/21
 */
public abstract class CookieUtil {
	private static Integer DEFAULT_EXPIRE_TIME = 365 * 24 * 3600;

	/**
	 * 获得cookie中 name的值
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getValue(String name) {
		return getValue(WebUtil.getRequest(), name);
	}

	/**
	 * 获得cookie中 name的值
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getValue(HttpServletRequest request, String name) {
		Cookie cookies[] = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * 添加一个cookie，默认过期时间为1天
	 * 
	 * @param response
	 * @param key
	 * @param value
	 */
	public static void addCookie(String key, String value) {
		addCookie(key, value, DEFAULT_EXPIRE_TIME);
	}

	/**
	 * 添加一个cookie
	 * 
	 * @param response
	 * @param key
	 * @param value
	 * @param expiry
	 */
	public static void addCookie(String key, String value, Integer expiry) {
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(expiry);
		cookie.setPath(WebUtil.getRequest().getContextPath());
		WebUtil.getResponse().addCookie(cookie);
	}
}
